<?php
namespace Seller\Controller;
use Admin\Logic\StoreLogic;
use Think\Page;

class FinanceController extends BaseController {
    
    /*
     * 初始化操作 
     */
    public function _initialize() {
       parent::_initialize();
    }    
    
   
    /**
     *  转账汇款记录
     */
    public function remittance(){
        $model = M("store_remittance");         
        $_GET = array_merge($_GET,$_POST);
        unset($_GET['create_time']);
        
        $user_id = I('user_id');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        
        $create_time = I('create_time');
        $create_time = str_replace("+"," ",$create_time);
        $create_time = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 year')).' - '.date('Y-m-d',strtotime('+1 day'));
        $create_time2 = explode(' - ',$create_time);
        $where = "store_id = ".STORE_ID." and create_time >= '".strtotime($create_time2[0])."' and create_time <= '".strtotime($create_time2[1])."' ";                     
        $user_id && $where .= " and user_id = $user_id ";
        $account_bank && $where .= " and account_bank like '%$account_bank%' ";
        $account_name && $where .= " and account_name like '%$account_name%' ";
                        
        $count = $model->where($where)->count();
        $Page  = new Page($count,2);
        $list = $model->where($where)->order("`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();        
        
        $this->assign('create_time',$create_time);        
        $show  = $Page->show();                 
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();    
    }
    
     /**
     * 异常订单导出
     */
    public function export_unusual()
    {

       $condition = [];$myw=' and a.store_id='.STORE_ID;

        
        $condition['a.store_id'] = STORE_ID;
        $session_fenbu = session('fenbu_id');
        $fenbu_id = I('fenbu_id');
        if($fenbu_id == '' && $session_fenbu == '0'){
            
             $fenbu = M('fenbu')->field('fenbu_id')->select();
            $fenbu_ids = '';
            foreach ($fenbu as $v){
                $fenbu_ids.= $v['fenbu_id'].',';
            }
            $fenbu_ids = substr($fenbu_ids,0,-1);
            $condition['a.ufenbu_id'] = ['in',$fenbu_ids];
        }else{
            if($session_fenbu == '0'){
                $condition['a.ufenbu_id'] = $fenbu_id;
            }else{
                $condition['a.ufenbu_id'] = session('fenbu_id');
            }
        }
       
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;

        I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;

        $condition['a.order_status'] = 1;//判断要列出的订单状态
        $condition['_string'] = '(a.order_status = 1 and a.jian_count > 0 and a.ruku_count != a.jian_count and a.ruku_count > 0) or (a.pda_qdzt = 1)';

        if(I('biaoshi_xian')){
            $condition['c.biaoshi_xian'] = I('biaoshi_xian');
            $myw.=' and c.biaoshi_xian="'.I('biaoshi_xian').'"';
        }


        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                $myw.=" AND a.tag_price <> 0 ";
            }
        }

        if(I('unusual_type')){
            if(I('unusual_type') == 1){
                $condition['a.pda_qdzt'] = 0;
                $myw.=' and a.pda_qdzt=0';
            }else{
                $condition['a.pda_qdzt'] = 1;
                $myw.=' and a.pda_qdzt=1';
            }
        }


        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }else{
            $begin = $this->begin;
            $end = $this->end;
        }

        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
            $myw.=' and a.add_time > "'.$begin.' " and  a.add_time < "'.$end.'" ' ;
        }
  
        //获取订单列表
        $orderList = M('order a')
            ->field('a.order_id,a.user_id,c.nickname,c.company,CONCAT(c.biaoshi_xian,if(c.fast_flag="1","快","")) as biaoshi_xian')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)
            ->order('a.order_id desc')
            ->group('a.user_id')->select(); //过滤获取主订单

  
        foreach($orderList as $key=>$v) { //整理子单
            $order_list = M('order a')
                ->field('a.order_id,a.pda_qdzt,a.order_status,a.jian_count,a.ruku_count as ruku_count,a.order_sn,a.store_id,a.jian_count,a.order_amount,a.pda_qdzt,a.tag_price,c.nickname,c.company,d.store_name,CONCAT(c.biaoshi_xian,if(c.fast_flag="1","快","")) as biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.ruku_last_time')
                ->join('ty_users c on a.user_id=c.user_id', 'LEFT')
                ->join('ty_store d on a.store_id=d.store_id', 'LEFT')
                ->where('a.user_id=' . $v['user_id'] . ' and a.order_status=1  and a.jian_count > 0 and a.ruku_count != a.jian_count'. $myw)
                ->group('a.order_id')
//                 ->group('b.order_id')
                ->order('a.order_id desc')
                ->select(); //过滤获取主订单
            $xiaoji = $i=0;;
            foreach ($order_list as $keys => $values) { //整理子单
                $rukunum = $values[$this->z.'ruku_count'];
                $chukunum = $values[$this->z.'chuku_count'];
                $order_list[$keys]['ruku'] = $rukunum;
                $order_list[$keys]['chuku'] = $chukunum;
                $order_list[$keys]['pda_online'] = $values['pda_online']!=0 ?$values['pda_online'] : $values['order_amount'];
                $xiaoji += sanwei($values['order_amount']);
                $zongji+=$values['order_amount']+$values['yijia_heji'];
            }
            $orderList[$key]["xiaoji"] = $xiaoji;
            $orderList[$key]["order_list"] = $order_list;
        }



        $strTable ='<table style="width:210mm;table-layout:fixed" border="1">';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td style="text-align:center;font-size:12px;width:95px;height:35px;">序号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:100px;">客户名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:100px;">订单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:52px;">件数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:105px;">商家名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">回款状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:65px;">小计金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:65px;">合计金额</td>';

        $strTable .= '</tr>';

        foreach($orderList as $vs){
            $strTables='';$i++;
            foreach($vs['order_list'] as $vss){
                $strTables .= '<tr>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:100px">'.$vss['order_sn'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['jian_count'].'->'.$vss['ruku'].'->'.$vss['chuku'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['store_name'].'</td>';
                if($vss['tag_price']){
                    $strTables .= '<td style="text-align:center;font-size:12px;height:35px">已回款</td>';
                }else{
                    $strTables .= '<td style="text-align:center;font-size:12px;height:35px">未回款</td>';
                }
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px;color:red">'.($vss['order_amount']+$vss['yijia_heji']).'</td>';
                $strTables .= '</tr>';
            }


            $strTable .= '<tr style="border:1px solid #000">
		<td style="text-align:center;font-size:12px;border:1px;width:50px;">'.$i.'</td>
		<td style="text-align:center;font-size:12px;border:1px;width:100px;WORD-WRAP:break-all;">'.$vs['company'].$vss['biaoshi_xian'].'</td>
		<td colspan="5">
		<table width="650" border="1">
		'.$strTables.'
		</table>
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.($vs['xiaoji']).'</td>
		</tr>';
        }

        $strTable .= '<tr style="border:1px solid #000">
		<td colspan="6" style="text-align:right;font-weight:bold;height:32px">
		合计：
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.$zongji.'</td>
		</tr>';
        $strTable .='</table>';

        unset($orderList);
        downloadExcel($strTable,'异常订单');
        exit();
    }
            
    /**
     * 提现申请记录
     */
    public function withdrawals()
    {
        $model = M("store_withdrawals");
        $status = I('status');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        $create_time = I('create_time');
        $create_time = str_replace("+"," ",$create_time);
        $create_time = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 year')).' - '.date('Y-m-d',strtotime('+1 day'));
        $create_time2 = explode(' - ',$create_time);
        $where = "store_id = ".STORE_ID." and create_time >= '".strtotime($create_time2[0])."' and create_time <= '".strtotime($create_time2[1])."' ";

        if($status === '0' || $status > 0)
            $where .= " and status = $status ";
        $account_bank && $where .= " and account_bank like '%$account_bank%' ";
        $account_name && $where .= " and account_name like '%$account_name%' ";
                        
        $count = $model->where($where)->select();
		//计算合计金额
			$hejiprice=$tuihuo_heji=$shouxufei_heji=0;
			foreach($count as $v){
				$tuihuo_heji+=$v['th_money'];
				$hejiprice+=$v['money'];
                $shouxufei_heji+=$v['sxf_money'];
			}
        $list = $model->where($where)->order("`id` desc")->limit(0,20)->select();        
                
        $store = M('store')->where("store_id = ".STORE_ID)->find();
		$tuihuo_list=M('return_goods a')
		->field('a.*,b.goods_name,b.original_img')
		->join('ty_goods b on a.goods_id=b.goods_id','LEFT')
		->where('a.store_id='.STORE_ID.' and status=1')->select();
		$tuihuo=0;//echo \json_encode($tuihuo_list);
		foreach($tuihuo_list as $v){
			$tuihuo+=$v['member_goods_price']*$v['goods_num']*((100-$v['points'])/100);
		}
		
        $this->assign('hejiprice',$hejiprice);
		$this->assign('tuihuo_heji',$tuihuo_heji);
		$this->assign('shouxufei_heji',$shouxufei_heji);
        $this->assign('store',$store);
		$this->assign('tuihuo',$tuihuo);
        $this->assign('create_time',$create_time);
        $this->assign('list',$list);
        C('TOKEN_ON',false);        
        $this->display();    
    }
    
    /**
     * 添加提现申请
     */
    public function add_edit_withdrawals()
    {
        $id = I('id',0);
        $id = $id ? $id : 0;
        $Model = M('store');
        $withdrawals = $Model->where("store_id =".STORE_ID)->find();

         if(IS_POST)
         {
             // if($withdrawals['status'] == 1)
             //    $this->error('申请成功的不能再修改');
             
            // $Model->create();
             // if($Model->id)
             // {
                 $Model->where("store_id =".STORE_ID)->save([
					 'bank_name'=>I('bank_name'),
					 'account_bank'=>I('account_bank'),
					 'account_name'=>I('account_name')
				 ]);
             //}
			 // else
    //          {
    //             $Model->store_id = STORE_ID; //
    //             $Model->create_time = time();
    //             $Model->add();
    //          }             
             $this->success('保存完成',U('withdrawals'));
             exit();
          }
        // $withdrawals_max = M('store')->where(array('store_id'=>STORE_ID))->getField('store_money');
        $withdrawals_min = tpCache('basic.min');
        // $this->assign('withdrawals_max',$withdrawals_max);
        // $this->assign('withdrawals_min',$withdrawals_min);
        $this->assign('withdrawals',$withdrawals);
        $this->display('_withdrawals');
    }

    /**
     * 删除申请记录
     */
    public function delWithdrawals()
    {                        
        $id = I('id');
        $model = M("StoreWithdrawals"); 
        $model->where("id = $id and store_id =".STORE_ID." and status != 1")->delete(); 
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
        $this->ajaxReturn(json_encode($return_arr));
    } 
    
    /**
     * 修改编辑 申请提现
     */
    public  function editWithdrawals(){        
        $id = I('id');
        $model = M("withdrawals");
        $withdrawals = $model->find($id);
        $user = M('users')->where("user_id = {$withdrawals[user_id]}")->find();
        
        if(IS_POST)
        {
                $model->create();
                
                // 如果是已经给用户转账 则生成转账流水记录
                if($model->status == 1 && $withdrawals['status'] != 1)
                {                
                    if($user['user_money'] < $withdrawals['money'])
                    {
                        $this->error("用户余额不足{$withdrawals['money']}，不够提现");    
                        exit;
                    }
                    
                    
                    accountLog($withdrawals['user_id'], ($withdrawals['money'] * -1), 0,"平台提现");
                    $remittance = array(
                        'user_id' => $withdrawals['user_id'],
                        'bank_name' => $withdrawals['bank_name'],
                        'account_bank' => $withdrawals['account_bank'],
                        'account_name' => $withdrawals['account_name'],
                        'money' => $withdrawals['money'],
                        'status' => 1,
                        'create_time' => time(),
                        'admin_id' => session('admin_id'),
                        'withdrawals_id' => $withdrawals['id'],
                        'remark'=>$model->remark,
                    );
                    M('remittance')->add($remittance);
                }                
                $model->save();                               
                $this->success("操作成功!",U('Admin/Finance/remittance'),3);
                exit;
        }                      
 
       if($user['nickname'])        
           $withdrawals['user_name'] = $user['nickname'];
       elseif($user['email'])        
           $withdrawals['user_name'] = $user['email'];
       elseif($user['mobile'])        
           $withdrawals['user_name'] = $user['mobile'];            
       
       $this->assign('user',$user);
       $this->assign('data',$withdrawals);
       $this->display();           
    }  

	public function cs(){
        $storeLogic = new StoreLogic();
        echo $storeLogic->auto_transfer(48); // 自动结算
	}

    /**
     *  商家结算记录
     */
    public function order_statis(){
		//echo '<span style="color:red;margin-left:35px">活动期间技术顶峰作案，此功能优化调试中。。。</span>';
        $model = M("store_withdrawals");
        $create_date = I('create_date');
        $create_date = str_replace("+"," ",$create_date);
        $create_date2 = $create_date  ? $create_date  : date('Y-m-d',strtotime('-5 month')).' 00:00 - '.date('Y-m-d',strtotime('+1 month')).' 23:59';
        $create_date3 = explode(' - ',$create_date2);
        $where = "store_id = ".STORE_ID." and create_time >= '".strtotime($create_date3[0])."' and create_time <= '".strtotime($create_date3[1])."' ";
                        
        $count = $model->where($where)->select();
		//计算合计金额
        $hejiprice=$tuihuo_heji=$shouxufei_heji=$expenses=0;
			foreach($count as $v){
				$tuihuo_heji+=$v['th_money'];
				$hejiprice+=$v['money'];
                $shouxufei_heji+=$v['sxf_money'];
                $expenses+=$v['expenses'];
			}
			
        $Page  = new Page(count($count),16);
        $list = $model->where($where)->order("`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();        
        
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();
		$this->assign('hejiprice',$hejiprice);
		$this->assign('expenses',$expenses);
		$this->assign('tuihuo_heji',$tuihuo_heji);
        $this->assign('shouxufei_heji',$shouxufei_heji);
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();    
    }

    public function order_no_statis()
    {
        $create_date = I('create_date');
		$order_sn= I('order_sn');
        $create_date = str_replace("+"," ",$create_date);
        $create_date2 = $create_date ? $create_date : date('Y-m-d', strtotime('-1 month')) . ' - ' . date('Y-m-d', strtotime('+1 month'));
        $create_date3 = explode(' - ', $create_date2);
		//$where=array();
		//$where['add_time']
		if($order_sn){
			$where = array(
			    'store_id' => STORE_ID,
			    'add_time' => array(array('gt', strtotime($create_date3[0])), array('lt', strtotime($create_date3[1]))),
			    'pda_checkout' => 0,
				'order_sn'=>array('like','%'.$order_sn.'%')
			);
		}else{
			$where = array(
            'store_id' => STORE_ID,
            'add_time' => array(array('gt', strtotime($create_date3[0])), array('lt', strtotime($create_date3[1]))),
            'pda_checkout' => 0
        );
		}
        
		
		!empty($order_sn)?$order_sn:false;
		
        $model = M('order');
		$count=$model->where($where)->select();
		$heji_price=$p_price_count=0;
		foreach($count as $v){
			$order_goods=M('order_goods a')
			->field('a.*,b.goods_name,b.original_img')
			->join('ty_goods b on a.goods_id=b.goods_id','LEFT')
			->where('order_id='.$v['order_id'])->select();
			
			$p_price=0;
			foreach($order_goods as $vs){
				$p_price+=$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100;
			}
			$p_price=\floor($p_price*1000)/1000;
			$p_price_count+=$p_price;
			$heji_price+=$v['order_amount'];
		}
		
        $Page = new Page(\count($count), 16);
        $list = $model->where($where)->order("`add_time` desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
		foreach($list as $key=>$v){
			$order_goods=M('order_goods a')
			->field('a.*,b.goods_name,b.original_img')
			->join('ty_goods b on a.goods_id=b.goods_id','LEFT')
			->where('order_id='.$v['order_id'])->select();
			
			$p_price=0;
			foreach($order_goods as $vs){
				$p_price+=$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100;
			}
			$p_price=\sanwei($p_price);
			$list[$key]['p_price']=$p_price;
			$list[$key]['y_price']=$v['order_amount']-$p_price;
		}
		
        $this->assign('create_date', $create_date2);
        $show = $Page->show();
        $order_status = C('ORDER_STATUS');
        $shipping_status = C('SHIPPING_STATUS');
        $this->assign('shipping_status',$shipping_status);
        $this->assign('order_status',$order_status);
		$this->assign('heji_price', $heji_price);
		$this->assign('p_price_count', $p_price_count);
        $this->assign('show', $show);
        $this->assign('list', $list);
        C('TOKEN_ON', false);
        $this->display();
    }
	
    public function order_yes_statis()
    {
        $create_date = I('create_date');
		$order_sn= I('order_sn');
        $create_date = str_replace("+"," ",$create_date);
        $create_date2 = $create_date ? $create_date : date('Y-m-d', strtotime('-1 month')) . ' - ' . date('Y-m-d', strtotime('+1 month'));
        $create_date3 = explode(' - ', $create_date2);

		if($order_sn){
			$where = array(
			    'store_id' => STORE_ID,
			    'add_time' => array(array('gt', strtotime($create_date3[0])), array('lt', strtotime($create_date3[1]))),
			    'pda_checkout' => 1,
				'order_sn'=>array('like','%'.$order_sn.'%')
			);
		}else{
			$where = array(
            'store_id' => STORE_ID,
            'add_time' => array(array('gt', strtotime($create_date3[0])), array('lt', strtotime($create_date3[1]))),
            'pda_checkout' => 1
        );
		}
        
		
		!empty($order_sn)?$order_sn:false;
		
        $model = M('order');
		$count=$model->where($where)->select();
		$heji_price=$p_price_count=0;
		foreach($count as $v){
			$order_goods=M('order_goods a')
			->field('a.*,b.goods_name,b.original_img')
			->join('ty_goods b on a.goods_id=b.goods_id','LEFT')
			->where('order_id='.$v['order_id'])->select();
			
			$p_price=0;
			foreach($order_goods as $vs){
				$p_price+=$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100;
			}
			$p_price=\floor($p_price*1000)/1000;
			$p_price_count+=$p_price;
			$heji_price+=$v['order_amount'];
		}
		
        $Page = new Page(\count($count), 16);
        $list = $model->where($where)->order("`add_time` desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
		foreach($list as $key=>$v){
			$order_goods=M('order_goods a')
			->field('a.*,b.goods_name,b.original_img')
			->join('ty_goods b on a.goods_id=b.goods_id','LEFT')
			->where('order_id='.$v['order_id'])->select();
			
			$p_price=0;
			foreach($order_goods as $vs){
				$p_price+=$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100;
			}
			$p_price=\sanwei($p_price);
			$list[$key]['p_price']=$p_price;
			$list[$key]['y_price']=$v['order_amount']-$p_price;
		}
		
        $this->assign('create_date', $create_date2);
        $show = $Page->show();
        $order_status = C('ORDER_STATUS');
        $shipping_status = C('SHIPPING_STATUS');
        $this->assign('shipping_status',$shipping_status);
        $this->assign('order_status',$order_status);
		$this->assign('heji_price', $heji_price);
		$this->assign('p_price_count', $p_price_count);
        $this->assign('show', $show);
        $this->assign('list', $list);
        C('TOKEN_ON', false);
        $this->display();
}

    public function order_statis_shouhuo()
    {
		$id= I('id');
		$order_sn= I('order_sn');
        $model = M("order_statis a");
        $where = "a.store_id = ".STORE_ID." and a.withdrawals_id=".$id;
		if($order_sn){
			$where .= " and a.order_sn like '%".$order_sn."%'";
		}

        $count = $model
		->field('a.*,b.add_time,b.order_amount')
		->join('ty_order b on a.order_sn=b.order_sn','LEFT')
		->where($where)->select();
		//计算合计金额
			$dan_heji=$shi_heji=$kou_heji=$yin_heji=0;
			foreach($count as $v){
				$dan_heji+=$v['order_amount'];
				$shi_heji+=$v['order_totals'];
				$kou_heji+=$v['commis_totals'];
				$yin_heji+=$v['result_totals'];
			}
        $Page  = new Page(count($count),20);
        $list = $model
        ->field('a.*,b.order_id,b.order_amount,d.company,b.ruku_last_time,b.change')
        ->join('ty_order b on a.order_sn=b.order_sn','LEFT')
        ->join('ty_users d on b.user_id=d.user_id','LEFT')
        ->where($where)->order("b.ruku_last_time asc")
        ->limit($Page->firstRow.','.$Page->listRows)->select();
        
//        foreach($list as $key=>$v){
//        	$list[$key]['ruku_time']=M('order_jian')->where('order_id='.$v['order_id'])->getField('ruku_time');
//        }
		//$list= arraySort($total,'xiaoshoue', SORT_DESC);
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();
		$this->assign([
			'dan_heji'=>$dan_heji,
			'shi_heji'=>$shi_heji,
			'kou_heji'=>$kou_heji,
			'yin_heji'=>$yin_heji
		]);
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	}

    public function order_statis_tuihuo()
    {
		$id= I('id');
		$goods_name= I('goods_name');
        $where = "a.store_id = ".STORE_ID." and a.withdrawals_id=".$id;
		if($goods_name){
			$where .= " and (a.remark like '%".$goods_name."%' or order_sn like '%".$goods_name."%')";
		}

        $count =M("return_goods a") 
		->field('a.*,b.*,c.goods_name,c.original_img')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->where($where)->select();
		//计算合计金额
			$dsprice=$kou_heji=$yin_heji=$dan_heji=0;
			foreach($count as $v){
				$dsprice=(float)$v['member_goods_price']*(float)$v['goods_num']; //订单价
				$dan_heji+=$dsprice;
				$kou_heji+=$dsprice*($v['points']/100); //平台价
				$yin_heji+=$dsprice-($dsprice*($v['points']/100));
			}
			
        $Page  = new Page(count($count),20);
        $list =M("return_goods a") 
		->field('a.*,b.*,c.goods_name,c.original_img')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->where($where)->order("`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		
		foreach($list as $key=>$v){
			$list[$key]['dsprice']=(float)$v['member_goods_price']*(float)$v['goods_num']; //订单价
			$list[$key]['ptprice']=$list[$key]['dsprice']*($v['points']/100); //平台价
			$list[$key]['ptprices']=$list[$key]['dsprice']-$list[$key]['ptprice'];
			// $heji_ptprice+=$ptprice;
			// $heji_ptprices+=$ptprices;
		}
        
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();
		$this->assign([
			'dan_heji'=>$dan_heji,
			'kou_heji'=>$kou_heji,
			'yin_heji'=>$yin_heji
		]);
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	}

    public function order_statis_djiesuan()
    {
        
		$id= I('id');
		$type= I('type');
		$order_sn= I('order_sn');
		$order_status= I('order_status')?I('order_status'):'1,2';
		$create_date = I('create_date');
		$create_date = str_replace("+"," ",$create_date);
		$create_date2 = $create_date  ? $create_date  : date('Y-m-d',strtotime('-1 month')).' 00:00 - '.date('Y-m-d',strtotime('+1 month')).' 23:59';
		$create_date3 = explode(' - ',$create_date2);
        $create_date4=($create_date3[0]==$create_date3[1]) ? strtotime($create_date3[1])+86399 :strtotime($create_date3[1]);
		if($type == 1){
		    $where = "a.store_id = ".STORE_ID." and (d.withdrawals_id=0 or d.withdrawals_id is null) and c.status_r=1 and c.ruku_time >= '".strtotime($create_date3[0])."' and c.ruku_time <= '".$create_date4."' ";
		}else{
		    $where = "a.store_id = ".STORE_ID." and d.withdrawals_id!=0 and c.status_r=1 and c.ruku_time >= '".strtotime($create_date3[0])."' and c.ruku_time <= '".$create_date4."' ";
		}
        
		if($order_sn){
			$where .= " and a.order_sn like '%".$order_sn."%'";
		} 
		
		$where .= " and a.order_status in ($order_status)";
	 

        $count = M()->query("SELECT a.order_id,a.order_sn,a.order_status,d.withdrawals_id,a.order_amount,a.coupon_price,a.dai_type,
		(SELECT sum(b.goods_num*b.member_goods_price*b.points/100) from ty_order_goods b where b.order_id=a.order_id) as commis_totals,
		(SELECT (a.order_amount*b.points/100) from ty_order_goods b where b.order_id=a.order_id limit 1) as commis_totals_k,
		c.status_r,c.ruku_time,d.order_totals
		 from ty_order a 
		 INNER JOIN ty_order_jian c on a.order_id=c.order_id 
		 LEFT JOIN ty_order_statis d on a.order_sn=d.order_sn 
		 where $where group by a.order_sn");

		//计算合计金额
			$dan_heji=$kou_heji=$yin_heji=$shi_heji=0;
			foreach($count as $v){
				if($v['dai_type']==2){
					$kou_heji+=$v['commis_totals_k']; //$dan_heji+=0;
				}else{
					$kou_heji+=$v['commis_totals']; //
				}

				if($v['order_totals'] && $v['order_amount']!=$v['order_totals'])
					$shi_heji+=$v['order_totals'];
					else
					$shi_heji+=$v['order_amount']+$v['coupon_price'];
					
					$dan_heji+=$v['order_amount']+$v['coupon_price'];
			}
			
			$yin_heji=$shi_heji-$kou_heji;

        $Page  = new Page(count($count),20);
        $list = M()->query("SELECT a.change,a.order_id,a.admin_note,d.withdrawals_id,a.order_sn,a.order_status,a.order_amount,a.coupon_price,a.dai_type,
		(SELECT sum(b.goods_num*b.member_goods_price*b.points/100) from ty_order_goods b where b.order_id=a.order_id) as commis_totals,
		(SELECT (a.order_amount*b.points/100) from ty_order_goods b where b.order_id=a.order_id limit 1) as commis_totals_k,
		c.status_r,c.ruku_time,d.order_totals
		 from ty_order a 
		 INNER JOIN ty_order_jian c on a.order_id=c.order_id 
		 LEFT JOIN ty_order_statis d on a.order_sn=d.order_sn 
		 where $where group by a.order_sn ORDER BY c.ruku_time asc limit $Page->firstRow,$Page->listRows");
        // dump($where);
        foreach($list as $key=>$v){
            $list[$key]['order_amount'] = $v['order_amount'] + $v['coupon_price'];
			$list[$key]['commis_totals']=$v['dai_type']==2 ? $v['commis_totals_k'] : $v['commis_totals'];
			
			if($v['order_totals'] && $v['order_amount']!=$v['order_totals']){
			   
				$list[$key]['yingshou']=$v['order_totals']-$list[$key]['commis_totals'];
			}else{
				$list[$key]['yingshou']=$list[$key]['order_amount']-$v['commis_totals'];
				$list[$key]['order_totals']=$v['order_amount'] + $v['coupon_price'];
			}
		}
        // dump($list);
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();
		$order_status = C('ORDER_STATUS');
		$this->assign([
			'dan_heji'=>$dan_heji,
			'kou_heji'=>$kou_heji,
			'yin_heji'=>$yin_heji,
			'shi_heji'=>$shi_heji,
			'order_status'=>$order_status
		]);
// 		dump($order_status);
        $this->assign('show',$show);
        $this->assign('list',$list);
        $this->assign('type',$type);
        C('TOKEN_ON',false);
        $this->display();
	}

    public function export_statis_shouhuo()
    {
    	//搜索条件
		$id= I('id');
		$order_sn= I('order_sn');
        $model = M("order_statis a");
        $where = "a.store_id = ".STORE_ID." and a.withdrawals_id=".$id;
		if($order_sn){
			$where .= " and a.order_sn like '%".$order_sn."%'";
		}

        $orderList = $model
		->field('a.*,b.order_id,b.order_amount,b.ruku_last_time,b.consignee,b.change')
		->join('ty_order b on a.order_sn=b.order_sn','LEFT')
		->where($where)->order('b.ruku_last_time asc')->select();
//		foreach($orderList as $key=>$v){
//			$orderList[$key]['ruku_time']=M('order_jian')->where('order_id='.$v['order_id'])->getField('ruku_time');
//		}
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">客户</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单金额</td>';
//		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">平台收款</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">抹零金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">应收金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">入库时间</td>';
    	$strTable .= '</tr>';
    	

    	foreach($orderList as $val){
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['consignee'].'</td>';
//			$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['order_amount'].'</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['order_totals'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['commis_totals'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['change'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['result_totals'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i',$val['ruku_last_time']).'</td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'结算订单');
    	exit();
    }
	
    public function export_statis_tuihuo()
    {
    	//搜索条件
		$id= I('id');
		$goods_name= I('goods_name');
        $where = "a.store_id = ".STORE_ID." and a.withdrawals_id=".$id;
		if($goods_name){
			$where .= " and a.remark like '%".$goods_name."%'";
		}

        $orderList =M("return_goods a") 
		->field('a.*,c.goods_name,c.original_img,b.company')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->where($where)->order('id desc')->select();
		foreach($orderList as $key=>$v){
			$orderList[$key]['dsprice']=(float)$v['member_goods_price']*(float)$v['goods_num']; //订单价
			$orderList[$key]['ptprice']=$orderList[$key]['dsprice']*($v['points']/100); //平台价
			$orderList[$key]['ptprices']=$orderList[$key]['dsprice']-$orderList[$key]['ptprice'];
			// $heji_ptprice+=$ptprice;
			// $heji_ptprices+=$ptprices;
		}
		//echo \json_encode($condition);exit;
		
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">备注</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">买家</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">产品</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">单价</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单价</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">应扣金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货时间</td>';
    	$strTable .= '</tr>';
    	

    	foreach($orderList as $val){
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['order_sn'].' &nbsp;</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['remark'].' </td>';
			$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['company'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['member_goods_price'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_num'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;color:#f39c12;">'.$val['dsprice'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;color: blue;">'.$val['ptprice'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;color:red;">'.$val['ptprices'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i',$val['addtime']).'</td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'结算退货订单');
    	exit();
    }
	
}